package com.example.mybaseapp.ui.floatingview

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.mybaseapp.R

class FloatingWindowService : Service() {
    private lateinit var localBroadcastManager: LocalBroadcastManager
    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View

    private var initialX = 0
    private var initialY = 0
    private var initialTouchX = 0f
    private var initialTouchY = 0f

    override fun onCreate() {
        super.onCreate()

        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this)
        // Inflate the floating layout
        floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_window, null)

        // Set the layout parameters for the floating window
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )

        // Set the position of the floating window
        layoutParams.gravity = Gravity.TOP or Gravity.START
        layoutParams.x = 100
        layoutParams.y = 100

        // Add the view to the window
        windowManager.addView(floatingView, layoutParams)

        // Set button click listener
        val button: Button = floatingView.findViewById(R.id.floating_button)
        button.setOnClickListener {
            // Handle button click
            // You can add your desired action here
//            Toast.makeText(this, "这是一个悬浮窗",Toast.LENGTH_SHORT).show()
            // 启动原来的活动（如果存在，则将其置于前面）

//            localBroadcastManager.sendBroadcast(Intent("com.example.floating.localreceiver"))//使用本地广播来启动原来的界面；
            //            因为这个是在原来的界面，启动的时候就会多出一个FloatintViewActivity；应该是可以解决的
            val activityIntent = Intent(this, FloatintViewActivity::class.java)
            activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
            startActivity(activityIntent)
            stopSelf()
        }

        // Close the service when the floating view is clicked
//        floatingView.setOnClickListener {
//            stopSelf()
//        }

        // 设置触摸监听
        floatingView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    initialX = layoutParams.x
                    initialY = layoutParams.y
                    initialTouchX = event.rawX
                    initialTouchY = event.rawY
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    layoutParams.x = initialX + (event.rawX - initialTouchX).toInt()
                    layoutParams.y = initialY + (event.rawY - initialTouchY).toInt()
                    windowManager.updateViewLayout(floatingView, layoutParams)
                    true
                }
                else -> false
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::floatingView.isInitialized) {
            windowManager.removeView(floatingView)
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}